<?php

namespace AdminModule\Models;

/**
 * Trida pro praci s dlazdickami.
 *
 * @author David
 */
class Tile extends \Nette\Database\Table\Selection {

    private $filter = array('id_tile', 'code', 'width', 'height', 'price', 'action',
        'id_manufacturer', 'id_image', 'id_tile_type', 'inserted');

    public function __construct(\Nette\Database\Connection $connection) {
        parent::__construct('tiles', $connection);
    }

    public function filter(array $data) {
        return \array_intersect_key($data, \array_flip($this->filter));
    }

    public function getActions($type = null) {
        if ($type !== null) {
            $this->where('id_tile_type = ?', array($type));
        }
        return $this->where('action = ?', array(true))->order('id_tile_type, id_tile DESC');
    }

    public function getForShowroom(\Nette\Database\Table\ActiveRow $showroom) {
        $ids = $this->query("SELECT id_tile from tiles WHERE action = 0 AND id_manufacturer = {$showroom->id_manufacturer} AND id_tile NOT IN "
             . "(SELECT id_tile FROM showroom_has_tiles)")->execute()->fetchAll(\PDO::FETCH_COLUMN);
        if (\count($ids) > 0) {
            return $this->where("id_tile IN (" . implode(',', array_values($ids)) . ")");
        }
        return array();
    }
    
    public function getShowroomTiles(\Nette\Database\Table\ActiveRow $showroom) {
        $ids = $this->query("SELECT id_tile FROM showroom_has_tiles WHERE id_showroom = " . $showroom->id_showroom)->execute()->fetchAll(\PDO::FETCH_COLUMN);
        if (\count($ids) > 0) {
            return $this->where("id_tile IN (" . implode(',', array_values($ids)) . ")");
        }
        return array();
    }

    public function getAllWithoutActions() {
        return $this->where('action = ?', array(false))->order('id_tile_type');
    }

    public function insert($data) {
        parent::insert($this->filter($data));
    }

    public function update($data) {
        parent::update($this->filter($data));
    }

}
